package com.cyandpos.pad.pay.payList;

import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.widget.FrameLayout;


import com.changyi.device.printer.PrintManagerLib;
import com.cyandpos.pad.activity.PayActivity;
import com.cyandpos.pad.common.commondata.BaseResponse;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.common.commondata.PrintStringList;
import com.cyandpos.pad.common.netmanager.PosHttpManager;
import com.cyandpos.pad.http.OkHttpUtils;
import com.cyandpos.pad.posdata.Goods;
import com.cyandpos.pad.posdata.O2OPayDetail;
import com.cyandpos.pad.posdata.PosO2ORequest;
import com.cyandpos.pad.posdata.PosO2OResponse;
import com.cyandpos.pad.posdata.SubTicketItem;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.DateUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.ToastUtils;
import com.cyandpos.pad.utils.log.MessageLog;
import com.cyandpos.pad.utils.log.SDTools;
import com.google.gson.JsonObject;

import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;


public class JHAllPay extends FrameLayout {
    private PayActivity homeAct;
    private int pmtId=0;//付款方式的ID
    private Timer mTimer = new Timer();
    private TicketInfo mTicket;
    private PosO2ORequest posO2oRequest;
    private PosO2OResponse posO2oResponse;
    private int payMoney;
    private ProgressDialog dialog;
    private int unavailNum;
    private String o2oCode="";
    private int waitSum =0 ;

    public JHAllPay(PayActivity context, TicketInfo ticket, int mSelectedPmtId, int pay, String buyerCode) {
        super(context);
        this.homeAct = context;
        this.payMoney = pay;
        this.mTicket = ticket;
        this.o2oCode = buyerCode;
        this.pmtId = mSelectedPmtId;
        posO2oRequest = new PosO2ORequest();
        posO2oResponse = new PosO2OResponse();
        unavailNum = 0;

    }

    public void o2oConsume() {
        dialog = new ProgressDialog(homeAct);
        dialog.setCancelable(false);
        posO2oRequest.setOrderno(mTicket.getOrderNo());
        posO2oRequest.setAppCode("ALLVPAY");
        posO2oRequest.setPayCode(pmtId+"");
        if(mTicket.getOldOrderNo()!=null && mTicket.getOldOrderNo().length()>0){
            MessageLog.writeLog("聚合退款记录的原外部订单号为："+o2oCode);
            posO2oRequest.setAppType("REFUND");
            for(O2OPayDetail item : ErpCommonData.oldTicket.getJhList()){
                if(item.getOutTradeNo().equals(o2oCode)){
                    //以下两个退款二选一就可以
                    posO2oRequest.setOutTradeNo_Old(item.getOutTradeNo());
                    posO2oRequest.setTransactionId_Old(item.getTransactionId());
                    posO2oRequest.setTotalFee_Old(item.getTotalFee()+"");
                    posO2oRequest.setOldPosId(item.getSktno()+"");
                    posO2oRequest.setOrderTime_Old(item.getJysj()+"");
                    break;
                }
            }
        }else if (mTicket.isFSTH()){
            posO2oRequest.setAppType("REFUND");
            posO2oRequest.setOutTradeNo_Old(o2oCode);
            // posO2oRequest.setTransactionId_Old(o2oCode);
            posO2oRequest.setTotalFee_Old(payMoney+"");
            posO2oRequest.setOldPosId(mTicket.getSktno()+"");
            posO2oRequest.setOrderTime_Old("");
        }
        else{
            MessageLog.writeLog("聚合的付款码为："+o2oCode);
            posO2oRequest.setAppType("SALE");
            posO2oRequest.setBuyerCode(o2oCode);
        }
        String jlbh = mTicket.getJlbh() + "";
        if (jlbh.length() <= 6) {
            jlbh = CommonUtils.autoAddZero(jlbh, 6);
        }

        posO2oRequest.setOutTradeNo(mTicket.getSktno() +jlbh + DateUtils.getCurrentTimeStr());
        posO2oRequest.setPosId(mTicket.getSktno());
        //目前测试写死
        //  posO2oRequest.setPosId("cy789cy");
        posO2oRequest.setReceiptNo(mTicket.getJlbh());
        posO2oRequest.setTotalFee(payMoney+"");
        posO2oRequest.setPersonId(mTicket.getCasherInfo().getPersonId()+"");
        posO2oRequest.setAttach(getJson());
        posO2oRequest.setGuid(UUID.randomUUID().toString());
        posO2oRequest.setMch_Id("");
        o2oRequest();
    }

    private void o2oRequest() {
        if(!dialog.isShowing()){
            if(mTicket.getOldOrderNo().length()>0)
                dialog.setMessage("聚合退款中，请耐心等待……");
            else
                dialog.setMessage("聚合交易中，请耐心等待……");
            dialog.show();
        }

        PosHttpManager.O2OTraceRequestExecute(posO2oRequest,new OkHttpUtils.ResultCallback() {
            @Override
            public void onSuccess(JsonObject response) {
                BaseResponse<PosO2OResponse> baseResponse = BaseResponse.fromJson(response.toString(),PosO2OResponse.class);
                if (baseResponse.getCode().equals("0")) {
                    dialog.dismiss();
                    MessageLog.writeLog("聚合消费服务端返回的串为："+baseResponse.getData().toString());
                    try {
                        posO2oResponse= baseResponse.getData();
                        if(posO2oResponse.getReturnMsg().equals("等待付款中")){
                            posO2oRequest.setAppType("QUERY");
                            o2oRequest();
                        }else {
                            if(posO2oResponse.getTradeState().equals("等待付款中")){
                                //开始轮询规定的次数
                                waitSum++;
                                if (waitSum > 12) {
                                    dialog.dismiss();
                                    onFailure("付款超时或用户取消交易");
                                } else {
                                    mTimer.schedule(new TimerTask() {
                                        @Override
                                        public void run() {
                                            posO2oRequest.setAppType("QUERY");
                                            o2oRequest();
                                        }
                                    }, 5000);
                                }
                            }else{
                                //交易成功
                                try{
                                    dialog.dismiss();
                                    if (mTimer != null) mTimer.cancel();
                                    ToastUtils.showMsg("聚合交易成功！");//交易成功提示
                                    MessageLog.writeLog("---聚合消费成功后---");
                                    int traceType = (mTicket.getOldOrderNo()!=null && mTicket.getOldOrderNo().length()>0) ? 1 : 0;
                                    O2OPayDetail item = handleO2OData(posO2oResponse, traceType);
                                    completeTanpay(item);//生成付款方式

                                    SDTools.writeO2OTicket(item,4);//支付宝签购单写到本地
                                    SharedPreferences pref =homeAct.getSharedPreferences("JHID", 0);
                                    SharedPreferences.Editor prefEdit = pref.edit();
                                    prefEdit.putString("JHTransactionId",item.getJlbh());
                                    prefEdit.commit();

                                    for(int i=0;i<Integer.parseInt(ErpCommonData.allvpayPrintNum);i++){

                                        PrintManagerLib.initPrinter(homeAct, CommonUtils.getSystemModel())
                                                .initDevice()
                                                .printList(PrintStringList.printO2OList(item,mTicket));
                                    }
                                    //
                                }catch (Exception e){
                                    MessageLog.writeLog("---聚合消费成功后---catch原因为：" + e.getMessage().toString());
                                }

                            }

                        }
                    }catch (Exception e){
                        onFailure(baseResponse.getCode() + baseResponse.getMsg() + e.getMessage().toString());
                    }
                }else{
                    dialog.dismiss();
                    if (TextUtils.isEmpty(baseResponse.getTips())){
                        onFailure(baseResponse.getMsg());
                    }else {
                        onFailure(baseResponse.getTips());
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                MessageLog.writeLog("---聚合消费返回失败--原因为：" + msg);
                if(msg.equals("网络不可用")){
                    unavailNum++;
                    if(unavailNum>5){
                        onFailure("亲，断网啦！请检查网络状态");
                    }else{
                        mTimer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                posO2oRequest.setAppType("QUERY");
                                o2oRequest();
                            }
                        }, 5000);
                    }
                }else{
                    dialog.dismiss();
                    if(mTicket.getOldOrderNo().length()>0)
                        ToastUtils.showMsg( "聚合退款失败"+msg);
                    else
                        ToastUtils.showMsg("聚合支付失败"+msg);
                }
            }
        });
    }

    private String getJson() {
        String returnFlag = "";
        if(mTicket.getOldOrderNo().length()>0)
            returnFlag ="-";
        String jsonGoods = null;
        for(SubTicketItem sub : mTicket.getSubTickets()){
            for(Goods goods :sub.getGoodsList()){
                jsonGoods =  "{\"spbarcode\":\"" + goods.getBarCode()
                        + "\",\"spcode\":\"" + goods.getCode()
                        + "\",\"spname\":\"" + goods.getName()
                        + "\",\"splm\":\""// + req.goods_list[req.goods_list.Count - 1].goods_group
                        + "\",\"splmmc\":\"" //+ req.goods_list[req.goods_list.Count - 1].goods_catid
                        + "\",\"spsb\":\"" //+ req.goods_list[req.goods_list.Count - 1].goods_ppcode
                        + "\",\"lsdj\":\"" + MoneyUtils.getMoneyInt(goods.getPrice())
                        + "\",\"quantity\":\"" + returnFlag +goods.getSaleCount()
                        + "\",\"unit\":\"" + goods.getUnit()
                        + "\",\"obligate\":\"" + "" + "\"},";
            }
        }
        jsonGoods = "[" + jsonGoods.substring(0,jsonGoods.length() -1) +"]";

        return jsonGoods;
    }


    private O2OPayDetail handleO2OData(PosO2OResponse posO2oResponse, int type) {
        O2OPayDetail item = new O2OPayDetail();
        item.setTotalFee(MoneyUtils.getMoneyIntYuan(posO2oResponse.getActTotalFee()) + MoneyUtils.getMoneyIntYuan(posO2oResponse.getCouponFee())+ MoneyUtils.getMoneyIntYuan(posO2oResponse.getCouponFee_Shop()) );
        item.setJlbh(mTicket.getOrderNo());
        item.setSktno(mTicket.getSktno());
        item.setPaymentMethod(2);//1 微信  2 支付宝
        item.setSkyId(mTicket.getCasherInfo().getPersonId());
        item.setCouponFee(MoneyUtils.getMoneyIntYuan(posO2oResponse.getCouponFee())+ MoneyUtils.getMoneyIntYuan(posO2oResponse.getCouponFee_Shop()));
        item.setTradeType(type);//消费类型
        item.setTransactionId(posO2oResponse.getTransactionId());
        item.setOutTradeNo(posO2oResponse.getOutTradeNo());
        item.setUserNo(posO2oResponse.getUserId());
        item.setJysj(DateUtils.strToDateLong(posO2oResponse.getOrderTime()));
        item.setPayCode(pmtId);
        item.setMemo(posO2oResponse.getMemo());
        return item;
    }

    private void completeTanpay(O2OPayDetail item) {
        mTicket.getJhList().add(item);
        int totalZfbMoney = 0;
        for(O2OPayDetail o2oItem :mTicket.getJhList()){
            if(o2oItem.getPayCode() == pmtId ){
                totalZfbMoney += o2oItem.getTotalFee();
            }
        }
        ((PayActivity)homeAct).reqAddPayAndCommitNet(totalZfbMoney, false);//判读是否请求commit
    }

    /**
     * 商户订单号
     */
    public void o2oBl(){
        dialog = new ProgressDialog(homeAct);
        dialog.setCancelable(false);

        if(!dialog.isShowing()){
            dialog.setMessage("聚合补录查询交易中，请耐心等待……");
            dialog.show();
        }

        posO2oRequest.setReceiptNo(mTicket.getJlbh());
        posO2oRequest.setAttach(getJson());
        posO2oRequest.setGuid(UUID.randomUUID().toString());
        posO2oRequest.setPayCode(pmtId+"");
        posO2oRequest.setOrderno(mTicket.getOrderNo());

        posO2oRequest.setAppCode("ALLVPAY");
        posO2oRequest.setAppType("SALEQUERY");
        posO2oRequest.setOutTradeNo_Old(o2oCode);//补录商户订单号
        String jlbh = mTicket.getJlbh() + "";
        if (jlbh.length() <= 6) {
            jlbh = CommonUtils.autoAddZero(jlbh, 6);
        }
        posO2oRequest.setOutTradeNo(mTicket.getSktno() +jlbh + DateUtils.getCurrentTimeStr());
        posO2oRequest.setPersonId(mTicket.getCasherInfo().getPersonId()+"");
        posO2oRequest.setPosId(mTicket.getSktno()+"");
        posO2oRequest.setParam3(1+"");

        MessageLog.writeLog("聚合补录的商户订单号为："+posO2oRequest.getOutTradeNo_Old());

        PosHttpManager.O2OTraceRequestExecute(posO2oRequest,new OkHttpUtils.ResultCallback() {
            @Override
            public void onSuccess(JsonObject response) {
                BaseResponse<PosO2OResponse> baseResponse = BaseResponse.fromJson(response.toString(),PosO2OResponse.class);
                if (baseResponse.getCode().equals("0")) {
                    dialog.dismiss();
                    MessageLog.writeLog("聚合补录查询服务端返回的串为："+baseResponse.getData().toString());
                    try {
                        posO2oResponse= baseResponse.getData();
                        dialog.dismiss();
                        ToastUtils.showMsg("聚合补录交易成功！");//交易成功提示
                        MessageLog.writeLog("---聚合补录交易成功---");
                        int traceType = (mTicket.getOldOrderNo()!=null && mTicket.getOldOrderNo().length()>0) ? 4 : 3;
                        O2OPayDetail item = handleO2OData(posO2oResponse, traceType);
                        completeTanpay(item);//请求同步付款后生成收款方式
                    }catch (Exception e){
                        onFailure(baseResponse.getCode() + baseResponse.getMsg() + e.getMessage().toString());
                    }
                }else{
                    dialog.dismiss();
                    homeAct.isWxOrZfBBL=false;
                    if (TextUtils.isEmpty(baseResponse.getTips())){
                        onFailure(baseResponse.getMsg());
                    }else {
                        onFailure(baseResponse.getTips());
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                MessageLog.writeLog("---聚合补录返回失败--原因为：" + msg);
                dialog.dismiss();
                homeAct.isWxOrZfBBL=false;
                if(mTicket.getOldOrderNo().length()>0)
                    ToastUtils.showMsg( "聚合退款补录失败"+msg);
                else
                    ToastUtils.showMsg("聚合支付补录失败"+msg);
            }
        });
    }


}
